package test.test_7_15;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;

public class Demo04 {
    public static String password;
    public static String[] passwords = new String[(int) Math.pow(10, 3)];


    public static void main(String[] args) throws InterruptedException {
        //随机生成密码
        password = createRandomPassword(3);
        System.out.println("password:" + password);
        //启动穷举法线程
        Thread matchThread = new Thread() {
            @Override
            public void run() {
                matchPassword(password);
            }
        };
        matchThread.start();
        matchThread.join();

        //启动日志线程
        System.out.println(Arrays.toString(passwords));
        Thread logThread = new Thread() {
            @Override
            public void run() {
                try {
                    FileOutputStream out = new FileOutputStream("D:\\wangdao_study\\studyHard\\password.txt");
                    for (int i = 0; i < passwords.length; i++) {
                        if(passwords[i] != null) {
                            out.write(passwords[i].getBytes());
                            out.write("\r\n".getBytes());
                        }
                    }

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        //logThread.setDaemon(true);
        logThread.start();
        Thread.sleep(5000);

    }

    private static String createRandomPassword(int len) {
        //所有的可能性000-999
        String str = "123456789";
        char[] chars = new char[len];
        for (int i = 0; i < chars.length; i++) {
            //(int) (Math.random()*str.length())生成一个0-str.length的数
            chars[i] = str.charAt((int) (Math.random() * str.length()));
        }

        return new String(chars);
    }

    private static void matchPassword(String password) {
        //所有的可能性是000-999
        //列一个 不是就放入数组中

        for(int i = 0; i < passwords.length; i++) {
            String possiblePassword = String.format("%03d",i);
            System.out.println(possiblePassword);
            if(password.equals(possiblePassword)) {
                break;
            }else {
                passwords[i] = possiblePassword;
            }
        }
    }
}
